﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using SmallERP.MODEL.FoundationModel;
using SmallERP.DAL;
using SmallERP.MODEL.PaperManager;
using System.Data;
using System.Data.OleDb;

namespace SmallERP.HostBll.Com
{
    /// <summary>
    /// 相纸的管理逻辑类
    /// </summary>
    public class PaperInfo_BLL
    {
        /// <summary>
        /// 得到所有没有完成的相纸信息
        /// </summary>
        /// <returns></returns>
        public  List<PaperInfo_info> GetAllNotOverPaper()
        {
            List<PaperInfo_info> resultList = new List<PaperInfo_info>();
            int paperOverStatus = (int)SmallERP.COM.Status.PaperInfoStatus.Complete;
            //using (smallerpDataContext db = new smallerpDataContext())
            //{
            //    foreach (var p in db.PaperInfo.Where(p => p.Status != paperOverStatus).ToList())
            //    {
            //        if (!p.PaperFaceReference.IsLoaded)
            //        {
            //            p.PaperFaceReference.Load();
            //        }
            //        if (!p.PaperTypeReference.IsLoaded)
            //        {
            //            p.PaperTypeReference.Load();
            //        }
            //        resultList.Add(new PaperInfo_info()
            //        {
            //            AddTime = p.AddTime,
            //            Length = p.Length,//米
            //            PaperFaceName = p.PaperFace.PaperFaceName,
            //            PaperFaceID = p.PaperFace.PaperFaceId,
            //            PaperTypeID = p.PaperType.PaperTypeId,
            //            PaperTypeName = p.PaperType.PaperTypeName,
            //            Width = (p.Width*100)/2.54,
            //            Status = p.Status,
            //            PrintPaperId = p.PrintPaperId
            //        });
            //    }
            //}
            string QuerystrSql = "select AddTime,Length,PaperFaceName,PaperFaceId,PaperTypeId,PaperTypeName,Width,Status,PrintPaperId from "
                              + " PaperInfo,PaperFace,PaperType where PaperInfo.PaperTypeID=PaperType.PaperTypeID and paperface.PaperFaceId=PaperInfo.PaperFaceId ";
            DataTable tableQ = DAL.AccessHelper.dataTable(QuerystrSql);
            for (int i = 0; i < tableQ.Rows.Count; i++)
            {
                PaperInfo_info info = new PaperInfo_info();
                info.AddTime = Convert.ToDateTime(tableQ.Rows[i]["AddTime"]);
                info.Length = Convert.ToInt32(tableQ.Rows[i]["Length"]);
                info.PaperFaceName = Convert.ToString(tableQ.Rows[i]["PaperFaceName"]);
                info.PaperFaceID = Convert.ToInt32(tableQ.Rows[i]["PaperFaceID"]);
                info.PaperTypeID = Convert.ToInt32(tableQ.Rows[i]["PaperTypeID"]);
                info.PaperTypeName = Convert.ToString(tableQ.Rows[i]["PaperTypeName"]);
                info.Width = Convert.ToDouble(tableQ.Rows[i]["Width"]);
                info.Status = Convert.ToInt32(tableQ.Rows[i]["Status"]);
                info.PrintPaperId = Convert.ToInt32(tableQ.Rows[i]["PrintPaperId"]);
                resultList.Add(info);

            }

            
            return resultList;
        }

        /// <summary>
        /// 添加新的纸
        /// </summary>
        /// <param name="newList"></param>
        /// <param name="newPaperCodeList">新新的ID，用于打印条码</param>
        /// <returns></returns>
        public  int AddNewPaperInfo(List<PaperInfo_info> newList, out List<int> newPaperCodeList)
        {
            int result = 0;
            newPaperCodeList = new List<int>();
          
            //if (newList.Count > 0)
            //{
            //    using (smallerpDataContext db = new smallerpDataContext())
            //    {

            //        foreach (var pi in newList)
            //        {
            //            PaperInfo piNew = new PaperInfo()
            //            {
            //                AddTime = UnityMethod.GetSystemTime(),
            //                EndPaperLength = 0,
            //                InvalidationArea = 0,
            //                LastBordId = 0,
            //                LastLength = pi.Length,
            //                Length = pi.Length,
            //                LastPrintTime = DateTime.Now,
            //                PaperEndArea = 0,
            //                PrinterID = 0,
            //                Remark = "",
            //                Status = (int)SmallERP.COM.Status.PaperInfoStatus.New,
            //                Width = (pi.Width*2.54)/100,
            //                PaperFace = db.PaperFace.FirstOrDefault(pf => pf.PaperFaceId == pi.PaperFaceID),
            //                PaperType = db.PaperType.FirstOrDefault(pt => pt.PaperTypeId == pi.PaperTypeID),
            //                PaperTitleArea = 0,
            //                ValidationArea = 0
            //            };
            //            db.AddToPaperInfo(piNew);
            //            listT.Add(piNew);
            //        }

            //        try
            //        {
            //            db.SaveChanges();
            //            newPaperCodeList = listT.Select(p => p.PrintPaperId).ToList();
            //        }
            //        catch (Exception)
            //        {
            //            result = -2;
            //        }
            //    }
            //}
            //else
            //{
            //    result = -1;
            //}
            OleDbConnection oleconn = AccessHelper.OpenMyConnection();
            OleDbTransaction tran = oleconn.BeginTransaction(); ;

            bool isSuccess = true;
           
            foreach( PaperInfo_info paper in newList)
            {
                DateTime addTime = DateTime.Now;
                 string InsertPaperInfo="insert into PaperInfo (AddTime,EndPaperLength,InvalidationArea,LastBordId,LastLength,Length,LastPrintTime,PaperEndArea,PrinterID"
                + " Remark,Status,Width,PaperFaceID,PaperTypeID,PaperTitleArea,ValidationArea) values('" + addTime + "'" + "0" + dota + "0" + dota + "0" + dota + paper.Length + dota + paper.Length + dota + DateTime.Now + "0" + dota + "0" + dota + "" + dota + (int)SmallERP.COM.Status.PaperInfoStatus.New
                +dota+((paper.Width*2.54)/100)+dota+paper.PaperFaceID+dota+paper.PaperTypeID+dota+paper.PaperFaceID+")";
                 int insertRtn = DAL.AccessHelper.ExecuteNonQuery(InsertPaperInfo,oleconn, tran);
                 string QueryId = "SELECT PrintPaperId from PaperInfo where AddTime=#"+addTime+"#";
                 int paperID = (int)DAL.AccessHelper.ExecuteScalar(QueryId, oleconn,tran);
                 if (insertRtn == 0)
                 {

                     isSuccess = false;
                     break;
                 }
                 else
                 {
                     newPaperCodeList.Add(paperID);
                 }

            }
            if (isSuccess)
            {
                tran.Commit();
            }
            else
            {
                tran.Rollback();
                result = -1;
            }
            return result;
        }
        string dota = " , ";
        public  int ModifyPaperInfo(PaperInfo_info modfifyPI)
        {
            int result = 0;
            //using (smallerpDataContext db = new smallerpDataContext())
            //{
            //    PaperInfo pi = db.PaperInfo.FirstOrDefault(p => p.PrintPaperId == modfifyPI.PrintPaperId);
            //    if (pi != null)
            //    {
            //        pi.PaperFace = db.PaperFace.FirstOrDefault(pf => pf.PaperFaceId == modfifyPI.PaperFaceID);
            //        pi.PaperType = db.PaperType.FirstOrDefault(pt => pt.PaperTypeId == modfifyPI.PaperTypeID);
            //        pi.Length = modfifyPI.Length;
            //        pi.Width = (modfifyPI.Width*2.54)/100;
            //    }
            //    else
            //    {
            //        result = -1;
            //    }
            //    try
            //    {
            //        db.SaveChanges();
            //    }
            //    catch (Exception)
            //    {

            //        result = -2;
            //    }
            //}
            return result;
        }

        public  void DelPaper(PaperInfo_info _SelectedPaperInfo)
        {
            //if (_SelectedPaperInfo != null)
            //{
            //    using (smallerpDataContext db = new smallerpDataContext())
            //    {
            //        PaperInfo pi = db.PaperInfo.FirstOrDefault(p => p.PrintPaperId == _SelectedPaperInfo.PrintPaperId);
            //        if (pi != null)
            //        {
            //            db.DeleteObject(pi);
            //        }
            //        try
            //        {
            //            db.SaveChanges();
            //        }
            //        catch
            //        {

            //        }
            //    }
            //}
        }

        private string ConvertToIn(List<int> inlist)
        {
            string rtnStr = "";
            foreach (int value in inlist)
            {
                rtnStr += value + ",";

            }
            rtnStr = rtnStr.Trim(',');
            return rtnStr;
        }
        /// <summary>
        /// 查询某一范围的纸
        /// </summary>
        /// <param name="PrinterIds">打印机ID</param>
        /// <param name="PTId">纸面 ID</param>
        /// <param name="PFId">纸型ID</param>
        /// <param name="startTime">开始时间</param>
        /// <param name="endTime">结束时间</param>
        /// <returns></returns>
        public  List<PaperInfo_Info> GetSomePaperUseStat(List<int> PrinterIds, List<int> PTIds, List<int> PFIds, DateTime startTime, DateTime endTime)
        {
            List<PaperInfo_Info> resultList = new List<PaperInfo_Info>();
           
            int paperNewState=(int)SmallERP.COM.Status.PaperInfoStatus.New;
            //using (smallerpDataContext db = new smallerpDataContext())
            //{
            //    foreach (var pi in db.PaperInfo.Include("PaperFace").Include("PaperType").Where(p =>  p.Status != paperNewState&&p.LastPrintTime >= startTime && p.LastPrintTime <= endTime).ToList().Where(p => PrinterIds.Contains(p.PrinterID) && PFIds.Contains(p.PaperFace.PaperFaceId) && PTIds.Contains(p.PaperType.PaperTypeId) ).ToList())
            //    {
            //        if (!pi.PaperTypeReference.IsLoaded)
            //        {
            //            pi.PaperTypeReference.Load();
            //        }
            //        if (!pi.PaperFaceReference.IsLoaded)
            //        {
            //            pi.PaperFaceReference.Load();
            //        }
            //        if (!pi.PaperWasteRecords.IsLoaded)
            //        {
            //            pi.PaperWasteRecords.Load();
            //        }

            //        PaperInfo_Info pT = new PaperInfo_Info()
            //        {
            //            AddTime = pi.AddTime,
            //            LastPrintTime = pi.LastPrintTime,
            //            Length = pi.Length,
            //            PaperFaceName = pi.PaperFace.PaperFaceName,
            //            PaperTypeName = pi.PaperType.PaperTypeName,
            //            PaperId = pi.PrintPaperId,
            //            PrinterId = pi.PrinterID,
            //            Status = pi.Status,
            //            Width = pi.Width,
            //            UseRecords=new List<PaperRecords_Info> (),
            //            PrintBoardArea=pi.ValidationArea,
            //            BarCodeAndBBArea=pi.InvalidationArea
            //        };       
             
            //        foreach (var r in pi.PaperWasteRecords.ToList())
            //        {
            //            if (!r.PaperWasteTypeReference.IsLoaded)
            //            {
            //                r.PaperWasteTypeReference.Load();
            //            }
                        
            //            pT.UseRecords.Add(new PaperRecords_Info()
            //            {
            //                AddTime = r.CreateTime,
            //                Length = r.Length,
            //                PaperId = pi.PrintPaperId,
            //                RecordId = r.Id,
            //                RecordName = r.PaperWasteType.PaperOperationTypeName,
            //                RecordTypeId = r.PaperWasteType.Id,
            //                Status = r.Status,
            //                Width = r.Width

            //            });
            //            pT.WateLength += r.Length;
            //        }

            //        resultList.Add(pT);
            //    }
            //}
            string QuerystrSql = "select AddTime,Length,PaperFaceName,PaperFaceId,PaperTypeId,PaperTypeName,Width,Status,PrintPaperId from "
                            + " PaperInfo,PaperFace,PaperType where PaperInfo.PaperTypeID=PaperType.PaperTypeID and paperface.PaperFaceId=PaperInfo.PaperFaceId ";
            string paperCondition=ConvertToIn(PTIds);
            string paperTypeAdd="";
            if(!string.IsNullOrEmpty(paperCondition))
            {
                paperTypeAdd="and PaperTypeId in("+paperCondition+")";
            }
            string paperfaceCondition = ConvertToIn(PTIds);
            string paperfaceAdd = "";
            if (!string.IsNullOrEmpty(paperfaceCondition))
            {
                paperfaceAdd = "and PaperFaceId in(" + paperCondition + ")";
            }

            string printerCondition = ConvertToIn(PTIds);
            string printerAdd = "";
            if (!string.IsNullOrEmpty(printerCondition))
            {
                printerAdd = "and printerid in(" + printerCondition + ")";
            }
            QuerystrSql += paperTypeAdd + paperfaceAdd + printerAdd;
            DataTable tableQ = DAL.AccessHelper.dataTable(QuerystrSql);
            for (int i = 0; i < tableQ.Rows.Count; i++)
            {
                SmallERP.MODEL.PaperManager.PaperInfo_Info info = new SmallERP.MODEL.PaperManager.PaperInfo_Info();
                info.AddTime = Convert.ToDateTime(tableQ.Rows[i]["AddTime"]);
                info.Length = Convert.ToInt32(tableQ.Rows[i]["Length"]);
                info.PaperFaceName = Convert.ToString(tableQ.Rows[i]["PaperFaceName"]);
                //info.PaperFaceID = Convert.ToInt32(tableQ.Rows[i]["PaperFaceID"]);
                //info.PaperTypeID = Convert.ToInt32(tableQ.Rows[i]["PaperTypeID"]);
                info.PaperTypeName = Convert.ToString(tableQ.Rows[i]["PaperTypeName"]);
                info.Width = Convert.ToDouble(tableQ.Rows[i]["Width"]);
                info.Status = Convert.ToInt32(tableQ.Rows[i]["Status"]);
                info.PaperId = Convert.ToInt32(tableQ.Rows[i]["PrintPaperId"]);
                info.UseRecords = new List<PaperRecords_Info>();
                string QueryWast = "select * from PaperWasteRecords,PaperWasteType where PaperWasteRecords.PaperWasteTypeId=PaperWasteType.Id and PrintPaperId=" + info.PaperId;
                DataTable tableW = DAL.AccessHelper.dataTable(QuerystrSql);
                for (int j = 0; j < tableW.Rows.Count; j++)
                {
                    PaperRecords_Info prinfo = new PaperRecords_Info();
                    prinfo.AddTime = Convert.ToDateTime(tableQ.Rows[i]["CreateTime"]);
                    prinfo.Length = Convert.ToDouble(tableQ.Rows[i]["Length"]);
                    prinfo.PaperId = info.PaperId;
                    prinfo.RecordId = Convert.ToInt32(tableQ.Rows[i]["Id"]);
                    prinfo.RecordName = Convert.ToString(tableQ.Rows[i]["PaperOperationTypeName"]);
                    prinfo.Status = Convert.ToInt32(tableQ.Rows[i]["Status"]);
                    prinfo.Width = Convert.ToDouble(tableQ.Rows[i]["Width"]);
                    info.UseRecords.Add(prinfo);

                }
                resultList.Add(info);

            }


            return resultList;
            
        }
    }
}
